<script setup lang="ts">
import {ref, computed, watch} from 'vue'
import {useCartStore} from '../stores/cart.ts'
import {storeToRefs} from 'pinia'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {formatPrice} from "../util/formatPrice.ts";


const cart = useCartStore()
const router = useRouter()
const {items} = storeToRefs(cart)

// 勾选状态
const selected = ref<Record<string | number, boolean>>({})
watch(items, (list) => {
  list.forEach(it => {
    if (selected.value[it.id] === undefined) selected.value[it.id] = true
  })
}, {immediate: true})

const allChecked = computed({
  get: () => items.value.length > 0 && items.value.every(i => selected.value[i.id]),
  set: (val: boolean) => {
    items.value.forEach(i => {
      selected.value[i.id] = val
    })
  }
})

const selectedCount = computed(() => items.value.filter(i => selected.value[i.id]).length)
const subtotal = (item: { price: number; qty: number }) => item.price * item.qty
const goodsTotal = computed(() => items.value.reduce((s, i) => s + subtotal(i), 0))
const payableTotal = computed(() => goodsTotal.value)

// 数量增减
const inc = (item: any) => cart.updateQty(item.id, item.qty + 1)
const dec = (item: any) => cart.updateQty(item.id, Math.max(1, item.qty - 1))

const removeItem = (id: string | number) => {
  cart.remove(id)
  // 删除商品后，从选中状态中移除
  delete selected.value[id]
}

const removeSelected = () => {
  const itemsToRemove = items.value.filter(i => selected.value[i.id])
  itemsToRemove.forEach(i => {
    cart.remove(i.id)
    delete selected.value[i.id]
  })
}
const submitOrder = () => {
  // 获取选中的商品ID列表
  const selectedIds = items.value
      .filter(item => selected.value[item.id])
      .map(item => item.id)

  if (selectedIds.length === 0) {
    ElMessage.warning('请选择要下单的商品')
    return
  }

  // 跳转到订单页面，传递选中的商品ID
  router.push({
    path: '/order',
    query: {selectedIds: selectedIds}
  })
}
</script>

<template>
  <div class="cart-page">
    <div class="cart-card">
      <div class="cart-header">
        <div class="title">
          <el-icon><i class="el-icon-shopping-cart-2"/></el-icon>
          購物車
        </div>
      </div>

      <!-- 列表 -->
      <div class="table body" v-for="item in items" :key="item.id">
        <div class="cell info">
          <img class="thumb" :src="item.image" :alt="item.title"/>
          <div class="meta">
            <div class="name" :title="item.title">{{ item.title }}</div>
            <div class="qty-line">
              <span class="subtotal">HK$</span>
              <div class="subtotal">{{ formatPrice(subtotal(item)) }}</div>
              <span class="subtotal">元</span>
            </div>
          </div>
        </div>
        <div class="cell sum">
          <div>
            <el-button size="small" @click="dec(item)">-</el-button>
            <span class="qty-num">{{ item.qty }}</span>
            <el-button size="small" @click="inc(item)">+</el-button>
          </div>
          <div class="cell action">
            <el-button type="danger" plain size="small" @click="removeItem(item.id)">删除</el-button>
          </div>
        </div>
      </div>

      <div class="footer-bar">
        <div class="left">
          <el-checkbox v-model="allChecked">已选 ({{ selectedCount }})</el-checkbox>
          <el-button size="small" @click="removeSelected">批量刪除</el-button>
        </div>
        <div class="right">
          <div class="payable">應付總額: <span class="amount">HK$  </span><span class="amount">{{formatPrice(payableTotal)  }}</span></div>
          <el-button type="danger" size="large" @click="submitOrder">下單</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cart-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
}

.cart-card {
  background-color: #2c3e50;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, .08);
  overflow: hidden;
}

.cart-header {
  padding: 16px 20px;
  border-bottom: 1px solid rgba(224, 224, 224, 0.57);
}

.title {
  font-size: 16px;
  font-weight: 700;
  color: #d1d1d1;
}

.table {
  display: grid;
  align-items: center;
  gap: 12px;
  padding: 14px 20px;
}


.body {
  border-bottom: 1px solid rgba(224, 224, 224, 0.53);
}

.cell.info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.qty-line {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  margin-top: 6px;
}

.cell.sum {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.subtotal {
  font-weight: 700;
  color: #d1d1d1;
}

.thumb {
  width: 68px;
  height: 68px;
  object-fit: cover;
  border-radius: 6px;
}

.meta .name {
  font-weight: 600;
  color: #c7c7c7;
  max-width: 520px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.qty-num {
  color: #d1d1d1;
  display: inline-block;
  min-width: 24px;
  text-align: center;
}

.footer-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 20px 18px;
  border-top: 1px solid rgba(224, 224, 224, 0.54);
}

.left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.payable {
  color: #d1d1d1;
  font-weight: bold;
  font-size: 25px;
}

.amount {
  color: #d1d1d1;
  font-size: 20px;
  font-weight: 800;
  margin-left: 6px;
}

@media (max-width: 992px) {
  .meta .name {
    max-width: 320px;
  }
}

@media (min-width: 769px) {
  .table.body {
    grid-template-columns: 1fr 200px;
    align-items: center;
  }
}

@media (max-width: 768px) {
}

@media (max-width: 480px) {
  .cart-page {
    padding: 12px;
  }

  .table {
    padding: 10px;
  }

  .table.body {
    grid-template-columns: 1fr;
    gap: 10px;
    padding-bottom: 16px;
  }

  .thumb {
    width: 48px;
    height: 48px;
  }

  .meta .name {
    max-width: 100%;
    font-size: 13px;
  }

  .qty-num {
    min-width: 20px;
  }

  .footer-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .left {
    order: 2;
    justify-content: space-between;
  }

  .right {
    order: 1;
    justify-content: space-between;
  }

  .amount {
    font-size: 18px;
  }
}
</style>
